import Ids from 'ids';
import type Canvas from 'diagram-js/lib/core/Canvas'

export function createElement(type: string, properties: Record<string, any>, parent: any, bpmnFactory: any) {
  const element = bpmnFactory.create(type, properties)

  if (parent) {
    element.$parent = parent
  }

  return element
}

export function fitViewport(canvas: Canvas, center = true) {
  if (!canvas) return
  const vbox = canvas.viewbox()
  const outer = vbox.outer
  const inner = vbox.inner
  let newScale
  let newViewbox

  if (
    inner.x >= 0
    && inner.y >= 0
    && inner.x + inner.width <= outer.width
    && inner.y + inner.height <= outer.height
    && !center
  ) {
    newViewbox = {
      x: 0,
      y: 0,
      width: Math.max(inner.width + inner.x, outer.width),
      height: Math.max(inner.height + inner.y, outer.height),
    }
  } else {
    newScale = Math.min(
      1,
      outer.width / inner.width,
      outer.height / inner.height,
    )
    newViewbox = {
      x: inner.x + (center ? inner.width / 2 - outer.width / newScale / 2 : 0),
      y:
        inner.y + (center ? inner.height / 2 - outer.height / newScale / 2 : 0),
      width: outer.width / newScale,
      height: outer.height / newScale,
    }
  }

  canvas.viewbox(newViewbox)

  return canvas.viewbox().scale
}

export function nextId(prefix: string) {
  const ids = new Ids([ 32,32,1 ]);

  return ids.nextPrefixed(prefix);
}